﻿using DocumentFormat.OpenXml.Lite.SpreadsheetML;
using DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IO = System.IO;

namespace DocumentFormat.OpenXml.Lite.Core.Office
{
    public static class Extensions
    {
        public static Workbook CreateSpreadsheet(this DocumentManager manager)
        {
            Guid id = DocumentFS.DocumentFS.CreateSandbox();

            SpreadsheetDocument doc = new SpreadsheetDocument(id, DocumentType.Excel);
            doc.CreateDefault();
            manager.AddDocument(id, doc);

            return doc.Workbook;
        }

        public static bool OpenExcelDocument(this DocumentManager manager, string path, out Workbook workbook)
        {
            if (IO.Path.GetExtension(path) != ".xlsx")
            {
                throw new OpenXmlException("Unknown OOXML file extension: '" + IO.Path.GetExtension(path) + "'!");
            }

            using (IO.FileStream fs = IO.File.Open(path, IO.FileMode.Open))
            {
                workbook = manager.OpenExcelDocument(fs);
                return workbook != null;
            }
        }

        public static Workbook OpenExcelDocument(this DocumentManager manager, IO.Stream stream)
        {
            try
            {
                Guid id = DocumentFS.DocumentFS.CreateSandbox();
                DocumentBase docBase = new SpreadsheetDocument(id, DocumentType.Word);

                docBase.CreateDefault();
                manager.AddDocument(id, docBase);

                if (manager.OpenDocument(stream, docBase))
                {
                    return (docBase as SpreadsheetDocument).Workbook;
                }
                return null;
            }
            catch (Exception ex)
            {
                throw new OpenXmlException("Cannot parse excel document. See inner exception for details.", ex);
            }
        }
    }
}
